/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.connection.parser.json.itemparsers;

import com.google.gjson.JSONException;
import com.google.gjson.JSONNumber;
import com.google.gjson.JSONObject;
import com.hercules.android.receiver.connection.parser.CommandParsingException;
import com.hercules.android.receiver.connection.parser.MalformedCommandException;

/**
 * Parser for integer properties.
 * <p>
 * AndroidAssembly2 this class was added in Android Assembly 2
 *
 * @author 7realm
 * @version 1.0
 */
public class IntegerParser extends FieldParser {
    /**
     * Constructor for {@link IntegerParser}.
     *
     * @param required if property is required
     */
    public IntegerParser(boolean required) {
        super(required);
    }

    /**
     * Parses integer property.
     *
     * @param path the path to value
     * @param json the JSON
     * @param keyName the name of current JSON key
     * @param instance the instance of object, parsed value will be set to it
     * @return the parsed value
     * @throws CommandParsingException if error occurs while parsing
     */
    @Override
    @SuppressWarnings("boxing")
    protected Object doParse(StringBuilder path, JSONObject json, String keyName, Object instance)
        throws CommandParsingException {
        try {
            // get value
        	JSONNumber value = json.get(keyName).isNumber();
            return value == null || value.isNull() != null ? 0 : (int) value.doubleValue();
        } catch (JSONException e) {
            throw new MalformedCommandException("Error occurred while parsing int field '" + path
                + "'. JSON: '" + json + "'.", e);
        }
    }
}
